<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;

use think\exception\ValidateException;
use think\facade\Log;

use util\Excel;
use util\Token;
use util\Upload;

/**
 * Costlogistics控制器
 */
class Costlogistics extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Costlogistics();

        $this->validate = \app\admin\validate\Costlogistics::class;
    }

    
    
    /**
     * 列表
     */
    public function index()
    {
        list($limit, $where, $sortArr) = $this->buildTableParames();
        $list = $this->model
            ->where($where)
            ->order('id desc')
            ->paginate($limit);

        $lists = $list->items();
        foreach ($lists as $k => $v) {
            switch ($v['status']) {
                case 'hidden':
                    $lists[$k]['status_name'] = '待匹配';
                    break;
                case 'normal':
                    $lists[$k]['status_name'] = '匹配成功';
                    break;
                default:
                    $lists[$k]['status_name'] = '未知';
            }
            if(!empty($v['timedate'])){
                $lists[$k]['timedate'] = date('Y-m', $v['timedate']);
            }else{
                $lists[$k]['timedate'] = '更早之前';
            }
        }

        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $lists,
        ];
        return json($data);
    }

    /**
     * 上传文件
     */
    public function uploads()
    {
        $file = $this->request->file('file');
        // try {
        $upload = new Upload();
        $res = $upload->upload($file);
        if ($res['url']) {
            // return success('ok', $res['url']);
            $return = $this->import_cost($res['url']);
            return success('ok', $return);
        } else {
            return error($res['msg']);
        }
        // } catch (\Exception $e) {
        //     Log::error("---ajax---upload--error:" . $e);
        // }
        return error('上传文件失败');
    }

    //导入花费
    public function  import_cost($url)
    {
        $url_arr = explode('storage/', $url);
        $data = Excel::import('storage/' . $url_arr[1]);
        unset($data[1]);
        $arr_insert = array();
        foreach ($data as  $value) {
            $arr_insert[] = [
                'transfer_number' => isset($value[0]) ? $value[0] : 0,
                'freight' => isset($value[1]) ? $value[1] : 0,
                'transfer' => isset($value[2]) ? $value[2] : '',
                'timedate' => strtotime(date('Y-m-1', time())),
            ];
        }
        if(!empty($arr_insert)){
            table('order_logistics')->insertAll($arr_insert);
        }
        return $url;
    }
}
